//
//  HttpConnectionHandler.m
//
//  Created by Allen Thomas on 9/14/10.
//

#import "HttpConnectionHandler.h"


@implementation HttpConnectionHandler

@synthesize username;
@synthesize password;
@synthesize receivedData;
@synthesize delegate;
@synthesize callback;
@synthesize errorCallback;
@synthesize url;

+ (id)withURL:(NSURL *)aUrl andUsername:(NSString *)aUsername andPassword:(NSString *)aPassword {
	HttpConnectionHandler *retConnectionHandler = [[HttpConnectionHandler alloc] init];
	[retConnectionHandler autorelease];
	
	retConnectionHandler.url = aUrl;
	retConnectionHandler.username = aUsername;
	retConnectionHandler.password = aPassword;
	
	return retConnectionHandler;
}

-(void)performHttpRequest:(id)requestDelegate withRequestSelector:(SEL)requestSelector {
	// Set the delegate and selector	
	self.delegate = requestDelegate;
	self.callback = requestSelector;
	[self processRequest];	
}


-(void)processRequest {	
	theRequest   = [[NSMutableURLRequest alloc] initWithURL:url];
	[theRequest setTimeoutInterval:20.0];
	[theRequest addValue:self.username forHTTPHeaderField:@"username"];
	[theRequest addValue:self.password forHTTPHeaderField:@"password"];
	[theRequest setHTTPMethod:@"POST"];
	
	NSLog(@"Request with headers username:%@ password:%@", [theRequest valueForHTTPHeaderField:@"username"], [theRequest valueForHTTPHeaderField:@"password"]);
	
	theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
	
	if (theConnection) {
		// Create the NSMutableData that will hold
		// the received data
		// receivedData is declared as a method instance elsewhere
		receivedData=[[NSMutableData data] retain];
	} else {
		NSLog(@"Problem with Connection");
		NSMutableDictionary *errorDictionary = [[ NSMutableDictionary alloc]
											 init];
		[errorDictionary setObject:@"Cannot connect to CMS Server" forKey:@"NSLocalizedDescriptionKey"];
		
		NSError *myConnectionError = [NSError errorWithDomain:@"com.bvcms.search" code:400 userInfo:errorDictionary];
		
		if(errorCallback) {
			[delegate performSelector:errorCallback withObject:myConnectionError];
		}
		
		[receivedData release];
		[theConnection release];
		[theRequest release];
		[errorDictionary release];
	}
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
	NSLog(@"challenged");
	
	if ([challenge previousFailureCount] == 0) {
        NSURLCredential *newCredential;
        newCredential=[NSURLCredential credentialWithUser:[self username]
                                                 password:[self password]
                                              persistence:NSURLCredentialPersistenceNone];
        [[challenge sender] useCredential:newCredential
               forAuthenticationChallenge:challenge];
		
    } else {
        [[challenge sender] cancelAuthenticationChallenge:challenge];
        // inform the user that the user name and password
        // in the preferences are incorrect
		NSLog(@"Invalid Username or Password");
		NSMutableDictionary *errorDictionary = [[ NSMutableDictionary alloc]
												init];
		[errorDictionary setObject:@"Secure connection authorization error" forKey:@"NSLocalizedDescriptionKey"];
		
		NSError *myConnectionError = [NSError errorWithDomain:@"com.bvcms.search" code:400 userInfo:errorDictionary];
		
		if(errorCallback) {
			[delegate performSelector:errorCallback withObject:myConnectionError];
		}

		[receivedData release];
		[errorDictionary release];
		[theConnection release];
		[theRequest release];
    }
	
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	NSLog(@"Received Response");
	[receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	NSLog(@"Received Data");
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
	[receivedData release];
    [theConnection release];
	[theRequest release];
	
    // inform the user
    NSLog(@"Connection failed! Error - %@",
          [error localizedDescription]);
	
	if(errorCallback) {
		[delegate performSelector:errorCallback withObject:error];
	}
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	NSLog(@"Finished Loading");

    // do something with the data
	if(delegate && callback) {
		if([delegate respondsToSelector:self.callback]) {
			[delegate performSelector:self.callback withObject:receivedData];
		} else {
			NSLog(@"No response from delegate");
		}
	} 
	
	// release the connection, and the data object
	[receivedData release];
	[theConnection release];
	[theRequest release];
}

-(void) dealloc {
	NSLog(@"Dealloc hch");
	[username release];
	[password release];
	[url release];
	[super dealloc];
}

@end
